#include "esp_common.h"
#include "spi.h"
#include "gpio.h"

void spi_init(void)
{
	    GPIO_ConfigTypeDef* cfg;
        
        cfg = (GPIO_ConfigTypeDef*)zalloc(sizeof(GPIO_ConfigTypeDef));
        printf("GPIO Config\n");

        /*MISO*/
        cfg->GPIO_Pin = SPI_MISO_PIN;
        cfg->GPIO_Mode = GPIO_Mode_Input;
        cfg->GPIO_Pullup = GPIO_PullUp_DIS;
        cfg->GPIO_IntrType = GPIO_PIN_INTR_DISABLE;
        gpio_config(cfg);
        /*MOSI*/
        cfg->GPIO_Pin = SPI_MOSI_PIN;
        cfg->GPIO_Mode = GPIO_Mode_Output;
        cfg->GPIO_Pullup = GPIO_PullUp_DIS;
        cfg->GPIO_IntrType = GPIO_PIN_INTR_DISABLE;
        gpio_config(cfg);
        /*CLK*/
        cfg->GPIO_Pin = SPI_CLK_PIN;
        cfg->GPIO_Mode = GPIO_Mode_Output;
        cfg->GPIO_Pullup = GPIO_PullUp_DIS;
        cfg->GPIO_IntrType = GPIO_PIN_INTR_DISABLE;
        gpio_config(cfg);
        /*CS*/
        cfg->GPIO_Pin = SPI_CS_PIN;
        cfg->GPIO_Mode = GPIO_Mode_Output;
        cfg->GPIO_Pullup = GPIO_PullUp_EN;
        cfg->GPIO_IntrType = GPIO_PIN_INTR_DISABLE;
        gpio_config(cfg);
        /*RST*/
        cfg->GPIO_Pin = BLE_RST_PIN;
        cfg->GPIO_Mode = GPIO_Mode_Output;
        cfg->GPIO_Pullup = GPIO_PullUp_DIS;
        cfg->GPIO_IntrType = GPIO_PIN_INTR_DISABLE;
        gpio_config(cfg);
        /*IRQ*/
        cfg->GPIO_Pin = BLE_IRQ_PIN;
        cfg->GPIO_Mode = GPIO_Mode_Input;
        cfg->GPIO_Pullup = GPIO_PullUp_DIS;
        cfg->GPIO_IntrType = GPIO_PIN_INTR_POSEDGE;
        gpio_config(cfg);

}

uint8_t spi_send_byte(uint8_t data)
{
	uint8_t i = 0, tmp = 0;

	for(i = 8; i > 0; i--)
	{
		if(data & 0x80)
			MOSI_H;
		else
			MOSI_L;

		data <<= 1;

		CLK_H;
		//vTaskDelay(1 / portTICK_RATE_MS);

		tmp <<= 1;
		if(gpio_input_get() & SPI_MISO_PIN)
			tmp+=1;

		CLK_L;
		//vTaskDelay(1 / portTICK_RATE_MS);
	}

	return tmp;
}

void bluenrg_bringup(void)
{
	uint8_t tmp = 0x0b, i, tmp1;

	RST_L;
	vTaskDelay(10 / portTICK_RATE_MS);
	RST_H;
	vTaskDelay(10 / portTICK_RATE_MS);
	while(!(gpio_input_get() & BLE_IRQ_PIN)){

	};
	/*Step1*/
	CS_L;
	tmp1 = spi_send_byte(tmp);
	printf("tmp1:%x\n",tmp1);
	tmp = 0x00;
	for(i = 0; i < 4; i++){
		tmp1 = spi_send_byte(tmp);
		printf("tmp1:%x\n",tmp1);
	}	
	CS_H;
	
	CS_L;
	tmp = 0x0b;
	tmp1 = spi_send_byte(tmp);
	printf("tmp1:%x\n",tmp1);
	tmp = 0x00;
	for(i = 0; i < 4; i++){
		tmp1 = spi_send_byte(tmp);
		printf("tmp1:%x\n",tmp1);
	}	
	CS_H;

	/*Step2*/
	CS_L;
	tmp = 0x0b;
	tmp1 = spi_send_byte(tmp);
	printf("tmp1:%x\n",tmp1);
	tmp = 0x00;
	for(i = 0; i < 10; i++){
		tmp1 = spi_send_byte(tmp);
		printf("tmp1:%x\n",tmp1);
	}
	CS_H;	
}

void spi_test(void)
{
	
	uint8_t tmp_buf[20], length;

	#if 0
	bluenrg_bringup();
	#endif

	#if 1
	length = 5;
	while(bluenrg_spi_read(tmp_buf, &length) == 0x01){
		printf("bluenrg read try again !\n");
	}
	#endif
}